/* eslint-disable @iceworks/best-practices/recommend-polyfill */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Table, Divider, Switch, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable, runInAction } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
import OperationChargeForm from './OperationChargeForm';
import PlatformChargeForm from './PlatformChargeForm';
import moment from 'moment';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const FromItem = Form.Item;

const ScPriceForm = ({ priceId, modal, onSubmit, onCancel }) => {
  const { scPriceStore: store } = useStore();
  const [operationCompany, setOperationCompany] = useState([]);
  const [platformCompany, setPlatformCompany] = useState([]);
  const [idx, setIdx] = useState();
  const [operationCharge, setOperationCharge] = useState();
  const [platformCharge, setPlatformCharge] = useState();
  const [startStation, setStartStation] = useState(null);
  const [endStation, setEndStation] = useState(null);
  const [companyList, setCompanyList] = useState(null);
  const [noticeList, setNoticeList] = useState(null);
  const [shift, setShift] = useState({});
  const isViewMode = modal[0] === 'view';
  const formProps = isViewMode ? { field: false } : {};
  const [price] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      await store.getCompany();
      if (priceId) {
        const data = await store.get(priceId);
        const { startMainArea, endMainArea, startMinorAreas, endMinorAreas } = data;
        const { siteMapping } = await store.getStationShuttle(data.startMinorAreas?.[0]);
        const companyIds = [];
        Object.keys(siteMapping).forEach((key) => {
          companyIds.push(key);
        });
        await store.getStartStation({ city: startMainArea });
        await store.getEndStation({ city: endMainArea, companyIds });
        const res = await store.getShifts({ search: { history: 0, shiftDate: moment().add('1', 'day').utc().format('YYYY-MM-DD'), routePriceId: priceId, findTypes: [3] } }) || [];
        setShift(res[0]);
        const operatingCompany = data.operatingCompany?.map((item) => ({
          ...item,
          specificSingleFare: item.companyId !== 'platform' ? res[0]?.price?.RMB - item.specificSingleFare?.RMB : 0,
          specificReturnFares: item.companyId !== 'platform' ? (res[0]?.price?.RMB - item.specificSingleFare?.RMB) * 2 : 0,
          specificSingleFareDifference: item.specificSingleFare?.RMB,
          specificReturnFaresDifference: item.specificReturnFares?.RMB,
          specificSinglePreferentialPrice: item.fareOtherInfo?.specificSinglePreferentialPrice,
          specificReturnPreferentialPrice: item.fareOtherInfo?.specificReturnPreferentialPrice,
          preferentialPriceTimePeriod: [item?.fareOtherInfo?.from, item?.fareOtherInfo?.to],
        }));
        const params = {};
        _.assign(params, {
          fromCities: [startMainArea],
          toCities: [endMainArea],
          fromStation: '',
          priceType: '3',
        });
        const start = await store.getBusStation({ ...params, direction: 0 });
        const companies = await store.getCompanies({ search: { isOperating: true }, pg: { page: 0, size: 999 } });
        const notice = await store.getNoticeUsers();
        setCompanyList(companies);
        setNoticeList(notice);
        setStartStation(start);
        operatingCompany.forEach(async (item) => {
          if (item.companyId === 'platform') {
            setPlatformCompany((pre) => [...pre, item]);
            const end = await store.getBusStation({ ...params, direction: 1 });
            setEndStation(end);
          } else {
            setOperationCompany((pre) => [...pre, item]);
          }
        });
        editCtx.origin = _.cloneDeep(data);
        _.assign(price, {
          ...data,
          startMinorAreas: startMinorAreas?.[0],
          endMinorAreas: endMinorAreas?.[0],
          automaticTicketIssue: {
            ...data?.automaticTicketIssue,
            user: data?.automaticTicketIssue?.user?.accountId,
          },
        });
      } else {
        // 添加操作,设置默认值
        _.set(price, 'priceType', '2');
        _.set(price, 'portTypes', ['0']);
        _.set(price, 'state', true);
      }
    })();
  }, []);

  if (!price) return <></>;

  const overrideModel = {
    startMinorAreas: {
      ui: {
        renderer: (v) => <TauSimpleSelect value={v} data={store.startStation} />,
      },
    },
    endMinorAreas: {
      ui: {
        renderer: (v) => <TauSimpleSelect value={v} data={store.endStation} />,
      },
    },
    automaticTicketIssue: {
      companyId: {
        ui: {
          renderer: (v) => <TauSimpleSelect data={companyList} placeholder={t`请选择公司`} value={v} />,
        },
      },
      onStationId: {
        ui: {
          renderer: (v) => <TauSimpleSelect data={startStation} placeholder={t`请选择开始站点`} value={v} />,
          itemProps: { required: !!toJS(price?.automaticTicketIssue?.companyId) },
        },
      },
      offStationId: {
        ui: {
          renderer: (v) => <TauSimpleSelect data={endStation} placeholder={t`请选择结束站点`} value={v} />,
          itemProps: { required: !!toJS(price?.automaticTicketIssue?.companyId) },
        },
      },
      user: {
        ui: {
          renderer: (v) => <TauSimpleSelect data={noticeList} placeholder={t`请选择通知人`} value={v} />,
          itemProps: { required: !!toJS(price?.automaticTicketIssue?.companyId) },
        },
      },
    },
  };

  const operationColumns = [
    {
      title: t`运营公司`,
      dataIndex: 'companyId',
      width: 300,
      align: 'center',
      cell: (v) => store.operatingCompanys.find((p) => p.value === v)?.label,
    },
    {
      title: t`单程差价`,
      dataIndex: 'specificSingleFareDifference',
      width: 200,
      align: 'center',
    },
    {
      title: t`往返差价`,
      dataIndex: 'specificReturnFaresDifference',
      width: 200,
      align: 'center',
    },
    {
      title: t`操作`,
      align: 'center',
      width: 200,
      cell: (v, i, r) => (
        <>
          <Button type="primary" text onClick={() => handleOperationCharge(r)}>{t`编辑`}</Button>
          <Divider direction="ver" />
          <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteOperation(i)}>{t`删除`}</Button>
        </>
      ),
    },
  ];
  const platformColumns = [
    {
      title: t`运营公司`,
      dataIndex: 'companyId',
      width: 300,
      align: 'center',
      cell: (v) => store.operatingCompanys.find((p) => p.value === v)?.label,
    },
    {
      title: t`单程售价`,
      dataIndex: 'specificSingleFareDifference',
      width: 200,
      align: 'center',
    },
    {
      title: t`活动价格`,
      dataIndex: 'specificSinglePreferentialPrice',
      width: 200,
      align: 'center',
    },
    {
      title: t`活动价格有效期`,
      dataIndex: 'preferentialPriceTimePeriod',
      width: 400,
      align: 'center',
      cell: (v) => {
        let component = null;
        if (v?.length > 0) {
          const [from, to] = v;
          component = (
            <>
              <span>{from}</span>
              <br />
              <span>{to}</span>
            </>);
        } else {
          component = <></>;
        }
        return component;
      },
    },
    {
      title: t`往返售价`,
      dataIndex: 'specificReturnFaresDifference',
      width: 200,
      align: 'center',
    },
    {
      title: t`往返活动价格`,
      dataIndex: 'specificReturnPreferentialPrice',
      width: 200,
      align: 'center',
    },
    {
      title: t`启用`,
      dataIndex: 'enable',
      width: 120,
      align: 'center',
      cell: (v) => <Switch checked={v} unCheckedChildren={t`禁用`} checkedChildren={t`启用`} autoWidth size="small" />,
    },
    {
      title: t`操作`,
      align: 'center',
      width: 200,
      cell: (v, i, r) => (
        <>
          <Button type="primary" text onClick={() => handlePlatformCharge(r)}>{t`编辑`}</Button>
          <Divider direction="ver" />
          <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeletePlatform(i)}>{t`删除`}</Button>
        </>
      ),
    },
  ];

  const handleAddPlatform = () => {
    if (platformCompany.length >= 1) {
      Message.warning({ content: t`最多只能添加一个平台运营公司！` });
      return;
    }
    const data = {
      id: new Date().getTime(),
      companyId: 'platform',
      specificSingleFare: 0,
      specificReturnFares: 0,
      specificSingleFareDifference: 0,
      specificReturnFaresDifference: 0,
      specificSinglePreferentialPrice: 0,
      specificReturnPreferentialPrice: 0,
      preferentialPriceTimePeriod: [],
      enable: true,
    };
    if (priceId && (data.companyId !== 'platform')) {
      data.specificSingleFareDifference = shift?.price?.RMB || '0.00';
      data.specificReturnFaresDifference = (shift?.price?.RMB) * 2 || '0.00';
    }
    setPlatformCompany((pre) => {
      const cloneData = [...pre];
      cloneData.push(data);
      return cloneData;
    });
  };

  const handleAddOperation = () => {
    const data = {
      id: new Date().getTime(),
      companyId: 'HK1044',
      specificSingleFareDifference: 0,
      specificReturnFaresDifference: 0,
      enable: true,
    };
    if (priceId && (data.companyId !== 'platform')) {
      data.specificSingleFareDifference = shift?.price?.RMB || '0.00';
      data.specificReturnFaresDifference = (shift?.price?.RMB) * 2 || '0.00';
    } else {
      data.specificSingleFareDifference = 0;
      data.specificReturnFaresDifference = 0;
    }
    setOperationCompany((pre) => {
      const cloneData = [...pre];
      cloneData.push(data);
      return cloneData;
    });
  };

  const handleDeletePlatform = (i) => {
    setPlatformCompany((pre) => {
      const arr = [...pre];
      arr.splice(i, 1);
      return arr;
    });
  };

  const handleDeleteOperation = (i) => {
    setOperationCompany((pre) => {
      const arr = [...pre];
      arr.splice(i, 1);
      return arr;
    });
  };

  const handleOperationCharge = (values) => {
    setOperationCharge({
      values,
    });
  };

  const handlePlatformCharge = (values) => {
    setPlatformCharge({
      values,
    });
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    runInAction(async () => {
      let handled = false;
      if (name === 'startMinorAreas') {
        _.assign(price, {
          startMinorAreas: value,
          endMinorAreas: [],
        });
        const companyIds = [];
        const site = item.field.fieldsMeta[name].inputValues[2].siteMapping;
        Object.keys(site).forEach((key) => {
          companyIds.push(key);
        });
        if (price.endMainArea) {
          await store.getEndStation({ city: price.endMainArea, companyIds });
        }
        handled = true;
      }
      if (name === 'endMinorAreas') {
        _.set(price, 'endMinorAreas', value);
        handled = true;
      }

      if (!handled) _.set(price, name, value);
      // 联动效果可以在这里通过设置price属性实现

      if (name === 'startMainArea') {
        _.unset(price, 'startMinorAreas');
        await store.getStartStation({ city: value });
        _.assign(price, {
          endMinorAreas: [],
          startMinorAreas: [],
        });
      }

      if (name === 'endMainArea') {
        _.assign(price, {
          endMinorAreas: [],
        });
        _.unset(price, 'endMinorAreas');
        await store.getEndStation({ city: value, companyIds: store.companyIds });
      }

      if (name === 'cprice.oneTripPrice.RMB' || name === 'cprice.roundTripPrice.RMB') {
        const prefix = _.trimEnd(name, '.RMB');
        _.set(price, `${prefix}.HKD`, parseFloat(value));
        _.set(price, `${prefix}.MOP`, parseFloat(value));
      }

      if (name === 'automaticTicketIssue.onStationId') {
        const { startMainArea, endMainArea } = toJS(price);
        const end = await store.getBusStation({
          fromCities: [startMainArea],
          toCities: [endMainArea],
          fromStation: value,
          direction: 1,
          priceType: '3',
        });
        setEndStation(end);
        _.set(price, 'automaticTicketIssue.offStationId', '');
      }
    });

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const operationChargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    setOperationCompany((pre) => {
      const newCharge = [...pre];
      newCharge[idx] = values;
      return newCharge;
    });
    setOperationCharge(false);
  };

  const platformChargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    setPlatformCompany((pre) => {
      const newCharge = [...pre];
      newCharge[idx] = values;
      return newCharge;
    });
    setPlatformCharge(false);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = async (_value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    if ((operationCompany?.length + platformCompany?.length) === 0) {
      return Dialog.confirm({
        content: t`运营公司不能为空!`,
      });
    }
    if (hasDuplicateIds(operationCompany)) {
      return Dialog.confirm({
        content: t`运营公司不可重复设置!`,
      });
    }
    const mergeCompany = [...operationCompany, ...platformCompany];
    const findState = mergeCompany.map((item) => {
      const { companyId } = item;
      const find = store.operatingCompanys.find((p) => p.value === companyId);
      if (find) {
        item.companyName = find.label;
      }
      return item;
    });
    // 后端不加字段 往单回程往返价里面添加字段
    const parseOC = findState.map((item) => ({
      ...item,
      fareOtherInfo: {
        // 单程优惠价
        specificSinglePreferentialPrice: item.specificSinglePreferentialPrice,
        // 往返优惠价
        specificReturnPreferentialPrice: item.specificReturnPreferentialPrice,
        from: (item.preferentialPriceTimePeriod && item.preferentialPriceTimePeriod?.length !== 0) ? item.preferentialPriceTimePeriod[0] : '',
        to: (item.preferentialPriceTimePeriod && item.preferentialPriceTimePeriod?.length !== 0) ? item.preferentialPriceTimePeriod[1] : '',
      },
      specificSingleFare: {
        RMB: Number(item.specificSingleFareDifference),
        MOP: Number(item.specificSingleFareDifference),
        HKD: Number(item.specificSingleFareDifference),
      },
      specificReturnFares: {
        RMB: Number(item.specificReturnFaresDifference),
        MOP: Number(item.specificReturnFaresDifference),
        HKD: Number(item.specificReturnFaresDifference),
      },
    }));
    // 删除不必要字段
    for (const item of parseOC) {
      delete item.preferentialPriceTimePeriod;
      delete item.specificSinglePreferentialPrice;
      delete item.specificReturnPreferentialPrice;
    }
    price.operatingCompany = parseOC;

    // 合并通知方身份信息
    if (platformCompany.length > 0) {
      const user = await store.getUserInfo(price?.automaticTicketIssue?.user);
      _.set(price, 'automaticTicketIssue', {
        ...toJS(price.automaticTicketIssue),
        user,
      });
    }
    onSubmit?.(price);
  };

  /**
   * 校验是否存在重复公司
   * @param {*} array
   * @returns true
   */
  function hasDuplicateIds(array) {
    return new Set(array.map((item) => item.companyId)).size !== array.length;
  }

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      value={price}
      colon
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基础信息`} />
      <FieldsGrid
        formData={price}
        mode={modal[0]}
        overrideModel={overrideModel}
        fields={['startMainArea', 'startMinorAreas', 'endMainArea', 'endMinorAreas', 'state']}
      />
      <TitleGrid title={t`线路信息`} />
      <FieldsGrid
        formData={price}
        mode={modal[0]}
        fields={['predictTime', 'mileage'].map((n) => `cprice.${n}`)}
      />
      <TitleGrid title={t`运营公司`} />
      <>
        <Button type="primary" style={{ marginBottom: 10 }} onClick={() => handleAddOperation()}>{t`添加运营公司`}</Button>
        <Table
          hasBorder={false}
          dataSource={operationCompany}
          columns={operationColumns}
          onRowClick={(__, index) => setIdx(index)}
        />
      </>
      <>
        <Button type="primary" style={{ marginBottom: 10 }} onClick={() => handleAddPlatform()}>{t`添加平台运营公司`}</Button>
        <Table
          hasBorder={false}
          dataSource={platformCompany}
          columns={platformColumns}
          onRowClick={(__, index) => setIdx(index)}
        />
      </>

      {platformCompany.length > 0 && (
        <>
          <TitleGrid title={t`关联运营公司线路信息`} />
          <FieldsGrid
            formData={price}
            mode={modal[0]}
            overrideModel={overrideModel}
            fields={['companyId', 'onStationId', 'offStationId', 'user'].map((p) => `automaticTicketIssue.${p}`)}
          />
        </>
      )}

      <TitleGrid title={t`其他`} />
      <FieldsGrid
        formData={price}
        mode={modal[0]}
        fields={['remarks']}
      />
      <Dialog
        visible={!!operationCharge}
        onCancel={() => setOperationCharge(false)}
        onClose={() => setOperationCharge(false)}
        title={t`编辑内容`}
        style={{ width: '30%' }}
        footer={null}
      >
        <OperationChargeForm
          data={operationCharge}
          onSubmit={(r, errors) => operationChargeOnSubmit(r, errors)}
          onCancel={() => setOperationCharge(false)}
        />
      </Dialog>
      <Dialog
        visible={!!platformCharge}
        onCancel={() => setPlatformCharge(false)}
        onClose={() => setPlatformCharge(false)}
        title={t`编辑内容`}
        style={{ width: '30%' }}
        footer={null}
      >
        <PlatformChargeForm
          data={platformCharge}
          onSubmit={(r, errors) => platformChargeOnSubmit(r, errors)}
          onCancel={() => setPlatformCharge(false)}
        />
      </Dialog>
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(ScPriceForm);
